package listNodePractice.jianxinjinke;

import java.util.List;

class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
            this.next = null;
        }
    }

//TODO:2023/11/4java  给出  将一个链表中所有的偶数节
// 点合并到该节点前面和它相邻的奇数节点上，新节点权值为两节点权值之和，直到剩余节点无法合并为止

public class MergeWithOdd {
    //TODO:2023/11/6  上面这个是gpt给的看不出来
        public static ListNode mergeEvenWithOdd(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode odd = head;
            ListNode even = head.next;
            ListNode evenHead = even;
            while (even != null && even.next != null) {
                odd.next = even.next;
                odd = odd.next;
                even.next = odd.next;
                even = even.next;
            }
            odd = head;
            even = evenHead;

            while (even != null) {
                odd.val += even.val;
                odd = odd.next;
                even = even.next;
            }



            return head;
        }


        public static void printList(ListNode head) {
            ListNode current = head;
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            while (current != null) {
             sb.append(current.val+",");
                current = current.next;
            }
            sb.deleteCharAt(sb.length()-1);
            sb.append("}");
            System.out.println(sb.toString());
        }

    public static ListNode mergeEvenWithOdd1(ListNode head) {
     if (head==null||head.next==null){
         return  null;
     }
     //TODO:2023/11/6   11 月4日使用递归的形式   6日回顾
       ListNode  pre=head;
       ListNode  cur=pre.next;
       if (cur.val%2==0){
           if (pre.val%2==1){
               pre.val= pre.val+ cur.val;
               ListNode temp=cur.next;
               pre.next=temp;
               mergeEvenWithOdd1(temp);
           }
           else{
               mergeEvenWithOdd1(cur.next);
           }
       }else {
           mergeEvenWithOdd1(cur);
       }
     return  head;
    }


        public static void main(String[] args) {
            ListNode head = new ListNode(2);
            head.next = new ListNode(2);
            head.next.next = new ListNode(4);
            head.next.next.next = new ListNode(3);
            head.next.next.next.next = new ListNode(6);
            head.next.next.next.next.next = new ListNode(5);


            System.out.println("Original List:");
            printList(head);

            head = mergeEvenWithOdd1(head);

            System.out.println("Merged List:");
            printList(head);
        }
    }

